import React, {Component} from 'react';

import { checkAndGetDatas, comfirmText } from 'utils/tools';
import  SliderService from 'services/Slider';
import CommonService from 'services/CommonService'
import { SLIDER_TH } from 'config/table_config'; 

import ListTitleCon from 'components/commonCon/ListTitleCon';
import TableHeadCon from 'components/commonCon/TableHeadCon';
import TableBodyCon from './TableBodyCon';

import './index.scss';

const sliderService = new SliderService(),
      commonService = new CommonService(),
      cfmText = comfirmText ('SLIDER');

class SliderCon extends Component {

  constructor (props) {
    super (props);
    this.state = {
      title: '轮播图管理',
      sliderData: []
    }
  }

  componentDidMount () {
    this.getSliderData();
  }

  /* 获取轮播数据*/
  async getSliderData () {
    const res = await sliderService.getSliderData();
    const data = await checkAndGetDatas(this, res); //传入this如res进行判断操作
    this.setState({
      sliderData: data
    })
  }

  /* 刷新*/
  async refreshSliderData() {
    this.getSliderData();
  }

  /* 下架课程*/
  async onStatusClick (id, index) {
    const { sliderData } = this.state,
          status = sliderData[index].status,
          text = cfmText (status);

    const cfm = window.confirm(text);

    if(!cfm) {
      return; //取消就返回
    }

    switch(status) {
    case 0:
      sliderData[index].status = 1;
      break;
    case 1:
      sliderData[index].status = 0;
      break;
    default:
      break;
    }

    this.setState({
      sliderData
    }, async ()=> {
    const result = await commonService.changeDataStatus({
      id: id, 
      field: 'SLIDER',
      status: this.state.sliderData[index].status
    })
    console.log(result)
    const errorCode = +result.error_code;
    if(errorCode !== 0) {
      alert(
        status === 0 ? '上架轮播图失败!' : '下架轮播图失败！'
      )
    }
    })
  }

  render() {
    const { title, sliderData } = this.state; //良好习惯，一定要解构
    return (
      <div className="list-container">
        {/* 公共组件 */}
        <ListTitleCon 
          title={title} 
          onRefreshData={this.refreshSliderData.bind(this)} />
        <table className="list-table">
          <TableHeadCon thData={ SLIDER_TH } />
          <TableBodyCon
            sliderData={ sliderData }
            onStatusClick = { this.onStatusClick.bind(this)} 
          />
        </table>
      </div>
    )
  }
}

export default SliderCon;